package com.qi.xiaogangzai.integrationim;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

public class LoginActivity extends AppCompatActivity {
    private EditText mUserNameEdit;
    private EditText mUserPassEdit;
    private Button mRegisterBtn, mLoginBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mUserNameEdit = (EditText) findViewById(R.id.login_phone_et);
        mUserPassEdit = (EditText) findViewById(R.id.login_psd_et);
        mRegisterBtn = (Button) findViewById(R.id.register_native_btn);
        mRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                register();
            }
        });

        mLoginBtn=(Button)findViewById(R.id.login_native_btn);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EMClient.getInstance().login(mUserNameEdit.getText().toString().trim(), mUserPassEdit.getText().toString().trim(), new EMCallBack() {
                    @Override
                    public void onSuccess() {

                                Log.d("main", "登录聊天服务器成功！");
                                startActivity(new Intent(LoginActivity.this,MainActivity.class));


                    }

                    @Override
                    public void onError(int i, final String s) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + s, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });


            }
        });
    }

    //注册的方法 异步
    public void register() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(mUserNameEdit.getText().toString().trim(), mUserPassEdit.getText().toString().trim());
                    Log.e("LoginActivity", "注册成功");
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    Log.e("LoginActivity", "注册失败");
                }
            }
        }).start();

    }
}
